package com.chb.sso.service;

import com.chb.sso.feign.PatientFeign;
import com.hos.entity.his.Patient;
import com.hos.entity.sys.Menu;
import com.hos.entity.sys.User;
import com.chb.sso.feign.MenuFeign;
import com.chb.sso.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/7 17:50
 * @description:
 * @modified By:
 * @version:
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MenuFeign menuFeign;
    @Autowired
    private PatientFeign patientFeign;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        // 1.医生进行登录
        User user = userFeign.selectUserByPhone(phone);
        if (user != null) {
            // 2.根据用户id查询用户具有的权限
            List<Menu> menus = menuFeign.findMenusByUserId(user.getUserId());
            List<String> collect1 = menus.stream().distinct().map(Menu::getPercode)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            List<SimpleGrantedAuthority> collect = collect1.stream().distinct().map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(user.getPhone(), user.getPassword(), collect);
        }

        // 2.患者进行登录
        Patient patient = patientFeign.selectPatientByPhone(phone);
        if (patient != null) {
            List<SimpleGrantedAuthority> collect = new ArrayList<>();
            // 进行放行患者
            return new org.springframework.security.core.userdetails.User(patient.getPhone(), patient.getPassword(), collect);
        }

        return null;
    }
}